package lero.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

/**
 * 作者: lero
 * 日期：2018/7/17
 */

@Controller
@RequestMapping("/file")
public class FileOperationController {

    @RequestMapping(value = "/upload.do",method = RequestMethod.POST)
    @ResponseBody
    public HashMap upload(@RequestParam("file") MultipartFile[]  multipartFile) throws IOException {
        WebApplicationContext currentWebApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContext context = currentWebApplicationContext.getServletContext();
        String realPath = context.getRealPath("/articleImg/");
        File file = new File(realPath);
        if(!file.exists() || !file.isDirectory()){
            file.mkdirs();
        }
        String newFileName =null;
        String imgPath = null;
        if(multipartFile!=null){
            for(int i=0;i<multipartFile.length;i++){
               String filename = multipartFile[i].getOriginalFilename();
               // String newFileName = new String(filename.getBytes("utf-8"),"iso8859-1");
                newFileName = UUID.randomUUID().toString()+filename.substring(filename.lastIndexOf("."));
                imgPath ="/articleImg/"+newFileName;
                File dis = new File(file, newFileName);
                multipartFile[i].transferTo(dis);
            }
        }
        HashMap map = new HashMap();
        map.put("code",0); //0表示成功，其它失败
        map.put("msg","图片上传失败") ; //提示信息 //一般上传失败后返回
        HashMap dataMap = new HashMap();
        dataMap.put("src",imgPath);
        dataMap.put("title",newFileName);
        map.put("data",dataMap);
        return map;
    }



}
